<?php
/**
 * Created by PhpStorm.
 * User: zhenglong
 * Date: 2017/10/25
 * Time: 上午11:51
 */

namespace App\ZL\Traites;

use Illuminate\Support\Collection;

class UserAbility
{
    protected $user;

    public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

    public function user()
    {
        return $this->user;
    }

    public function roles($role = '')
    {
        $roles = $this->user()
            ->roles()
            ->get()
            ->keyBy('name');

        if (! $role) {
            return $roles;
        }

        return $roles->get($role, false);
    }

    public function all($ability = '')
    {
        $roles = $this->roles();
        $roles->load('abilities');
        $abilities = $roles->reduce(function ($collect, $role) {
            return $collect->merge(
                $role->abilities->keyBy('name')
            );
        }, new Collection());

        if (! $ability) {
            return $abilities;
        }

        return $abilities->get($ability, false);
    }
}